<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script type="text/javascript">
    // 解决回调地狱
    // 1. promise
    new Promise((resolve, reject) => {
      resolve('success')
      // 无效
      reject('reject')
    })
    // 当我们在构造 promise 的时候，构造函数内部的代码是立即执行的
    new Promise((resolve, reject) => {
      console.log('new Promise')
      resolve('success')
    })
    console.log('finish')

    Promise.resolve(1)
      .then(res => {
        console.log(res)
        return 2
      })
      .then(res => {
        console.log(res)
      })

      // 加载图片
      let preloadImage = function (path) {
        return new Promise((resolve, reject) => {
          let image = new Image()
          image.onload = resolve
          image.onerror = reject
          iamge.src = path
        })
      }

      // async await
      // 异步方法一
      function takeLongTime() {
        return new Promise((resolve, reject) => {
          setTimeout(()=> resolve(10), 1000)
        })
      }
      // 异步方法二
      function takeLongTime2(v) {
        console.log(v)
        return new Promise(resolve => {
          setTimeout(() => resolve(v + 20), 10)
        })
      }
      
      async function test() {
        // 先执行 takeLongTime 然后 执行 takeLongTime2
        // 将 takeLongTime 中得到的结果传给takleLongTime2中
        const v = await takeLongTime()
        const b = await takeLongTime2(v)
        console.log(b)
      }
      // 执行 test 方法
      test()
      // 输出结果为 10  30
  </script>
</body>
</html>